# -*- encoding:utf-8 -*-
# Author:Alano
# apps/utils/email_send.py
import string
from random import Random
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from users.models import EmailVerifyRecord
from django.conf import settings


# 生成随机字符串
def random_str(random_length=8):
    str = ''
    # 生成字符串的可选字符串
    chars = string.digits + string.ascii_letters
    length = len(chars) - 1
    random = Random()
    for i in range(random_length):
        str += chars[random.randint(0, length)]
    return str


# 发送注册邮件
def send_register_email(email, send_type="register"):
    # 发送之前先保存到数据库，到时候查询链接是否存在
    # 实例化一个EmailVerifyRecord对象
    email_record = EmailVerifyRecord()
    # 将邮箱、随机码、发送类型写入数据库
    code = random_str(16)
    email_record.code = code
    email_record.email = email
    email_record.send_type = send_type
    email_record.save()
    # 发送注册邮件
    if send_type == "register":

        # 指定邮件发送内容以及连接url
        email_title = "NBA注册激活链接"
        email_body = "请点击下面的链接激活你的账号: http://127.0.0.1:8000/active/{0}".format(code)
        try:
            # 使用Django内置函数完成邮件发送。四个参数：主题，邮件内容，发件人邮箱地址，收件人（是一个字符串列表）
            send_status = send_mail(email_title, email_body, settings.EMAIL_FROM, [email])

        # 如果检查到用户的输入带有头部注入攻击的可能性，会弹出BadHeaderError异常。
        except BadHeaderError:
            return HttpResponse('Invalid header found.')

        # 如果发送成功
        if send_status:
            return

    # 发送修改密码邮件
    elif send_type == "forget":
        email_title = "找回密码链接"
        email_body = "请点击下面的链接更改你账号的密码: http://127.0.0.1:8000/reset_pwd/{0}".format(code)
        try:
            send_status = send_mail(email_title, email_body, settings.EMAIL_FROM, [email])
        except BadHeaderError:
            return HttpResponse('Invalid header found.')
        if send_status:
            return

    # 发送邮箱修改验证码
    elif send_type == "update_email":
        email_title = "NBA邮箱修改验证码"
        email_body = "你的邮箱验证码为{0}".format(code)

        # 使用Django内置函数完成邮件发送。四个参数：主题，邮件内容，从哪里发，接受者list
        send_status = send_mail(email_title, email_body, settings.EMAIL_FROM, [email])
        # 如果发送成功
        if send_status:
            pass

    else:
        # In reality we'd use a form class
        # to get proper validation errors.
        return HttpResponse('Make sure all fields are entered and valid.')